package net.sureon.web.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.app.UserSession;
import net.sureon.biz.ApplicationMgr;
import net.sureon.biz.UserBO;
import net.sureon.biz.UserMgr;
import net.sureon.common.SureonConstants;
import net.sureon.dao.Application;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class MyConfirmApplication implements Controller {
	private ApplicationMgr applicationMgr;
	private UserMgr userMgr;

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		long userID = ((net.sureon.app.UserSession) request.getSession()
				.getAttribute(UserSession.HTTP_SESSION_KEY)).getUserID();

		long companyID = ((net.sureon.app.UserSession) request.getSession()
				.getAttribute(UserSession.HTTP_SESSION_KEY)).getCompanyID();
		
		String showContent = request.getParameter("showContent");
		if("true".equals(showContent)) {
			// 编辑
			long applicationID = Long.parseLong(request.getParameter("applicationID"));
			Application application = applicationMgr.getApplicationByID(companyID, applicationID);
			if(application != null) {
				request.setAttribute("application", application);
			}
		}
		
		int maxResults = SureonConstants.PAGE_SIZE;
		String cp = request.getParameter("currentPage");
		int currentPage = 1;
		if(!"".equals(cp)) {
			try {
				currentPage = Integer.parseInt(request.getParameter("currentPage"));
			} catch(Exception e) {
				
			}
		}
		
		int skipResults = (currentPage - 1) * maxResults;
		
		List<Application> all = null;
		all = applicationMgr.getApplicationByUserReview(companyID, userID, skipResults, maxResults);
		UserBO reviewer = null;
		for(Application app : all) {
			reviewer = userMgr.getUser(companyID, app.getReviewedBy());
			app.setReviewer(reviewer.getUserVO());
		}
		request.setAttribute("all", all);
		int pageCounter = (applicationMgr.getApplicationByUserReview(companyID, userID, 0, 10000).size() + SureonConstants.PAGE_SIZE - 1) / SureonConstants.PAGE_SIZE;
		request.setAttribute("currentPage", currentPage);
		request.setAttribute("pageCounter", pageCounter);
		
		return new ModelAndView("/user/myConfirmApplication");
	}

	public ApplicationMgr getApplicationMgr() {
		return applicationMgr;
	}

	public void setApplicationMgr(ApplicationMgr applicationMgr) {
		this.applicationMgr = applicationMgr;
	}

	public UserMgr getUserMgr() {
		return userMgr;
	}

	public void setUserMgr(UserMgr userMgr) {
		this.userMgr = userMgr;
	}
}
